package com.mamingchao.concurrent.cas;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * Created by mamingchao on 2020/7/16.
 * 限流作用
 * 信号量设置了通过的线程的上限，只有线程数上限内的线程，才能通过执行
 */
public class SemaphoreTest {

    static Semaphore s = new Semaphore(2,true);

    public static void main(String[] args) {
        for (int i=0;i<20;i++) {
            final String threadName = "T-" + i;

            new Thread(()->{
                try {
                    s.acquire();
                    TimeUnit.SECONDS.sleep(1);
                    System.out.printf("Thread %s is running....", threadName);
                    System.out.println();
                }catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    s.release();
                }
            }).start();
        }
    }
}
